package cs2340.todolist.controller;

import java.util.Date;
import java.util.List;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TimePicker;
import android.widget.ViewFlipper;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

import cs2340.todolist.R;
import cs2340.todolist.application.ToDoListApplication;
import cs2340.todolist.model.Location;
import cs2340.todolist.model.ToDoItem;
import cs2340.todolist.model.account_management.AccountManager;
import cs2340.todolist.model.account_management.ItemInformationManager;
import cs2340.todolist.model.sqlite_database.ToDoItemDataSource;
import cs2340.todolist.view.MapPin;


public class ItemInformationActivity extends MapActivity {
	
	private AccountManager accountManager;
	private ItemInformationManager ourIIM;
	private ToDoItem item;
	/**
	 * called when the activity is first created
	 */
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.item_information);

       
	}
	
	/**
	 * called whenever this activity is started
	 */
	public void onStart() {

		super.onStart();

		//grabs teh account manager from background application
        accountManager = ((ToDoListApplication)getApplication()).getSessionManager().getAccountManager();
        accountManager.changeContext(this);
        ourIIM = ((ToDoListApplication)getApplication()).getItemInformationManager();
        item = ourIIM.getCurrentItem();
        
        final EditText titleEditText = (EditText)findViewById(R.id.item_information_title);
        final Spinner typeSpinner = (Spinner)findViewById(R.id.item_information_type);	
        final DatePicker dueDatePicker = (DatePicker)findViewById(R.id.item_information_due_date);
        final TimePicker timePicker = (TimePicker)findViewById(R.id.item_information_time);
        final Spinner recurTypeSpinner = (Spinner)findViewById(R.id.item_information_recur_type);
        final EditText locationNameEditText = (EditText)findViewById(R.id.item_information_location);
        final EditText descriptionEditText = (EditText)findViewById(R.id.item_information_description);	
        final Switch completedSwitch = (Switch)findViewById(R.id.item_information_completed);
        final EditText addressEditText = (EditText)findViewById(R.id.item_information_enter_address);
        
        final ViewFlipper viewFlipper = (ViewFlipper)findViewById(R.id.item_information_view_flipper);
        viewFlipper.setAnimation(AnimationUtils.loadAnimation(ItemInformationActivity.this, android.R.anim.fade_out));
        
        final Button showMapButton = (Button)findViewById(R.id.item_information_show_map);
        showMapButton.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
                viewFlipper.showNext();
        	}
        });
        
        final Button returnFromMapButton = (Button)findViewById(R.id.item_information_map_view_return);
        returnFromMapButton.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
                viewFlipper.showPrevious();
        	}
        });
        
        
		final Button backToListButton = (Button) findViewById(R.id.item_information_cancel_button);
        backToListButton.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				//this brings up the login screen if the cancel button is pressed
				Intent homeScreenIntent = new Intent(ItemInformationActivity.this,HomeScreenActivity.class);
				startActivity(homeScreenIntent);
			}
        });
        
		final Button saveItemButton = (Button) findViewById(R.id.item_information_save_item_button);
		saveItemButton.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				//TODO: this saves the item to the database, deleting the old one and inserting this new one
	        	ToDoItemDataSource dataSource = new ToDoItemDataSource(ItemInformationActivity.this);
	        	
	        	dataSource.open();
	        	dataSource.updateItem(	item.getId(),
	        							accountManager.getCurrentUser().getId(),
										titleEditText.getText().toString(),
										new Location(locationNameEditText.getText().toString(), addressEditText.getText().toString()),
										typeSpinner.getSelectedItemPosition(),
										new Date(dueDatePicker.getYear(),dueDatePicker.getMonth(),dueDatePicker.getDayOfMonth(),timePicker.getCurrentHour(),timePicker.getCurrentMinute()), 
										recurTypeSpinner.getSelectedItemPosition(),
										descriptionEditText.getText().toString(),
										completedSwitch.isChecked());

	        	dataSource.close();
				Intent homeScreenIntent = new Intent(ItemInformationActivity.this,HomeScreenActivity.class);
				startActivity(homeScreenIntent);
			}
        });
		final MapView map = (MapView)findViewById(R.id.item_information_map_view);
        map.setBuiltInZoomControls(true);

		GeoPoint geoPoint = item.getLocation().geocode(this);
		MapPin mapPin = new MapPin(this);
		List<Overlay> mapOverlays = map.getOverlays();
		if(geoPoint != null) {
			mapPin.addOverlay(new OverlayItem(geoPoint, item.getTitle(), item.getLocation().toString()));
			mapOverlays.add(mapPin);
		}
		
        //fills in all the information for the current item to the screen
        titleEditText.setText(ourIIM.getTitle());
        typeSpinner.setSelection(ourIIM.getTypeInt());
        dueDatePicker.updateDate(item.getDueDate().getYear(), item.getDueDate().getMonth(), item.getDueDate().getDate());
        timePicker.setCurrentHour(item.getDueDate().getHours());
        timePicker.setCurrentMinute(item.getDueDate().getMinutes());
        recurTypeSpinner.setSelection(ourIIM.getRecurTypeInt());
        descriptionEditText.setText(ourIIM.getDescriptionString());
        completedSwitch.setChecked(ourIIM.getCompleted());
        locationNameEditText.setText(item.getLocation().getName());
        addressEditText.setText(item.getLocation().getAddr());
        addressEditText.setOnKeyListener(new OnKeyListener() {
            
            Thread currentThread;
			@Override
			public boolean onKey(View view, int keyCode, KeyEvent event) {
				
				if(currentThread == null || !currentThread.isAlive()) {
					map.getOverlays().clear();
			        map.invalidate();
					currentThread = new Thread() {
						 public void run() {
			                	try {
									Thread.sleep(800);
								} catch (InterruptedException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
			                	
			    				Location location = new Location(locationNameEditText.getText().toString(), addressEditText.getText().toString());
			    				GeoPoint geoPoint = location.geocode(ItemInformationActivity.this);
			    				MapPin mapPin = new MapPin(ItemInformationActivity.this);
			    				List<Overlay> mapOverlays = map.getOverlays();
			    				if(geoPoint != null) {
			    					mapPin.addOverlay(new OverlayItem(geoPoint, item.getTitle(), location.toString()));
			    					mapOverlays.add(mapPin);
			    					map.getController().animateTo(geoPoint);
			    					map.getController().setZoom(14);

			    				}
			    				
			    			}
					};
					currentThread.run();
					return false;
				}
				else return false;
			}
        	
        });
        
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	


}
